<template>
  <div class="app-container">
    <!-- 左侧类别菜单栏 -->
    <div class="sidebar">
      <div class="category-header">
        <h3>笔记分类</h3>
        <div class="category-actions">
          <button @click="addCategoryDialog" title="添加分类">+</button>
        </div>
      </div>
      <ul class="category-list">
        <li v-for="category in categories" :key="category.id" :class="{ active: currentCategoryId === category.id }">
          <div class="category-item" @click="toggleCategory(category)">
            <span class="category-name">{{ category.name }}</span>
            <span class="note-count">({{ getNoteCountByCategory(category.id) }})</span>
            <span class="toggle-icon">
              {{ expandedCategories[category.id] ? '−' : '+' }}
            </span>
            <button v-if="category.id !== 'all'" class="delete-category-btn"
              @click.stop="confirmDeleteCategory(category)" title="删除分类">
              ×
            </button>
          </div>
          <ul class="note-list" v-if="expandedCategories[category.id]">
            <li v-for="note in getNotesByCategory(category.id)" :key="note.id"
              :class="{ active: currentNoteId === note.id }" @click.stop="selectNote(note)">
              <span class="note-title-text">{{ note.title }}</span>
              <span class="note-date">{{ formatDate(note.updatedAt) }}</span>
              <div class="note-actions">
                <div class="more-actions-container">
                  <button class="more-actions-btn" @click.stop="toggleNoteActions(note.id)" title="更多操作">⋯</button>
                  <div class="more-actions-menu" v-if="activeNoteActions === note.id">
                    <button @click.stop="confirmMoveNote(note)">移动</button>
                    <button @click.stop="confirmDeleteNote(note)">删除</button>
                  </div>
                </div>
              </div>
            </li>
            <li class="add-note" @click.stop="createNewNote(category.id)">
              + 添加笔记
            </li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 主内容区域 -->
    <div class="markdown-container">
      <div class="toolbar">
        <button @click="saveNote" :disabled="!currentNoteId" title="保存笔记">保存</button>
        <button @click="exportNote('markdown')" :disabled="!currentNoteId" title="导出为Markdown">导出MD</button>
        <button @click="exportNote('html')" :disabled="!currentNoteId" title="导出为HTML">导出HTML</button>
        <button @click="openExportDirectory" :disabled="!currentNoteId" title="打开导出目录">导出目录</button>
        <span class="note-title" v-if="currentNote">
          {{ currentNote.title || '无标题笔记' }}
        </span>
      </div>

      <mavon-editor v-model="content" ref="mdEditor" :toolbars="markdownOption" style="height: calc(100vh - 60px)"
        @imgAdd="handleImageAdd" v-if="currentNoteId" />

      <div class="welcome-screen" v-else>
        <h2>欢迎使用笔记应用</h2>
        <p>请从左侧选择一个笔记或创建新笔记</p>
      </div>
    </div>

    <!-- 添加类别对话框 -->
    <div class="modal-overlay" v-if="showAddCategoryDialog" @click.self="showAddCategoryDialog = false">
      <div class="modal-content">
        <h3>添加新类别</h3>
        <input v-model="newCategoryName" placeholder="输入类别名称" @keyup.enter="addCategory" />
        <div class="modal-actions">
          <button @click="addCategory">确认</button>
          <button @click="showAddCategoryDialog = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 删除笔记确认对话框 -->
    <div class="modal-overlay" v-if="showDeleteConfirm" @click.self="showDeleteConfirm = false">
      <div class="modal-content">
        <h3>确认删除</h3>
        <p>确定要删除笔记 "{{ noteToDelete?.title || '无标题笔记' }}" 吗？此操作无法撤销。</p>
        <div class="modal-actions">
          <button @click="deleteNote">确认删除</button>
          <button @click="showDeleteConfirm = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 删除类别确认对话框 -->
    <div class="modal-overlay" v-if="showDeleteCategoryConfirm" @click.self="showDeleteCategoryConfirm = false">
      <div class="modal-content">
        <h3>确认删除类别</h3>
        <p>确定要删除类别 "{{ categoryToDelete?.name }}" 吗？</p>
        <p class="warning-text">该类别下的所有笔记将被移动到"全部笔记"中。</p>
        <div class="modal-actions">
          <button @click="deleteCategory">确认删除</button>
          <button @click="showDeleteCategoryConfirm = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 移动笔记对话框 -->
    <div class="modal-overlay" v-if="showMoveNoteDialog" @click.self="showMoveNoteDialog = false">
      <div class="modal-content">
        <h3>移动笔记</h3>
        <p>将 "{{ noteToMove?.title || '无标题笔记' }}" 移动到:</p>
        <select v-model="selectedTargetCategory" class="category-select">
          <option v-for="cat in availableTargetCategories" :key="cat.id" :value="cat.id">
            {{ cat.name }}
          </option>
        </select>
        <div class="modal-actions">
          <button @click="moveNote">确认移动</button>
          <button @click="showMoveNoteDialog = false">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { SaveNote, LoadNote, DeleteNote, GetNoteList, GetCategories, AddCategory, DeleteCategory, ExportNote, OpenExportDirectory, MoveNote } from '../../wailsjs/go/controller/NoteApp'

export default {
  components: {
    mavonEditor
  },
  data() {
    return {
      content: '',
      noteList: [],
      currentNote: null,
      currentNoteId: '',
      currentCategoryId: '',
      categories: [
        { id: 'all', name: '全部笔记' }
      ],
      expandedCategories: {},
      showAddCategoryDialog: false,
      newCategoryName: '',
      showDeleteConfirm: false,
      noteToDelete: null,
      showDeleteCategoryConfirm: false,
      categoryToDelete: null,
      showMoveNoteDialog: false,
      noteToMove: null,
      selectedTargetCategory: '',
      activeNoteActions: null, // 当前显示操作菜单的笔记ID
      markdownOption: {
        bold: true,
        italic: true,
        header: true,
        underline: true,
        strikethrough: true,
        mark: true,
        superscript: true,
        subscript: true,
        quote: true,
        ol: true,
        ul: true,
        link: true,
        imagelink: true,
        code: true,
        table: true,
        fullscreen: true,
        readmodel: true,
        htmlcode: true,
        help: true,
        undo: true,
        redo: true,
        trash: true,
        save: false,
        navigation: true,
        alignleft: true,
        aligncenter: true,
        alignright: true,
        subfield: true,
        preview: true,
      }
    }
  },
  async created() {
    await this.loadCategories()
    await this.loadNoteList()
    // 默认展开"全部笔记"类别
    this.expandedCategories['all'] = true
  },
  computed: {
    availableTargetCategories() {
      // 排除当前类别和"全部笔记"
      return this.categories.filter(
        cat => cat.id !== 'all' && cat.id !== (this.noteToMove?.category?.id || '')
      )
    }
  },
  mounted() {
    document.addEventListener('click', this.handleClickOutside)
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  methods: {

    toggleNoteActions(noteId) {
      this.activeNoteActions = this.activeNoteActions === noteId ? null : noteId
    },

    // 点击其他地方关闭操作菜单
    handleClickOutside(event) {
      const actionsContainer = event.target.closest('.more-actions-container')
      if (!actionsContainer) {
        this.activeNoteActions = null
      }
    },
    async loadCategories() {
      try {
        const dbCategories = await GetCategories()
        this.categories = [
          { id: 'all', name: '全部笔记' },
          ...dbCategories
        ]
        // 初始化展开状态
        this.categories.forEach(cat => {
          this.$set(this.expandedCategories, cat.id, false)
        })
      } catch (err) {
        console.error('加载类别失败:', err)
      }
    },

    async loadNoteList() {
      try {
        this.noteList = await GetNoteList()
      } catch (err) {
        console.error('加载笔记列表失败:', err)
      }
    },

    getNoteCountByCategory(categoryId) {
      if (categoryId === 'all') return this.noteList.length
      return this.noteList.filter(note => note.category?.id === categoryId).length
    },

    getNotesByCategory(categoryId) {
      if (categoryId === 'all') return this.noteList
      return this.noteList.filter(note => note.category?.id === categoryId)
    },

    toggleCategory(category) {
      this.$set(this.expandedCategories, category.id, !this.expandedCategories[category.id])
      this.currentCategoryId = category.id
    },

    async selectNote(note) {
      this.currentNoteId = note.id
      this.currentNote = note
      this.currentCategoryId = note.category?.id || 'all'
      try {
        const noteContent = await LoadNote(note.id)
        this.content = noteContent || '# 空笔记'
      } catch (err) {
        console.error('加载笔记失败:', err)
        this.content = '# 加载笔记失败\n\n请重试或创建新笔记'
      }
    },

    async saveNote() {
      if (!this.content.trim() || !this.currentNoteId) return

      try {
        const noteTitle = this.extractTitle(this.content)
        const categoryId = this.currentCategoryId === 'all' ? '' : this.currentCategoryId

        const result = await SaveNote(
          this.currentNoteId,
          noteTitle,
          this.content,
          categoryId
        )

        if (result) {
          await this.loadNoteList()
          // 更新当前笔记信息
          const updatedNote = {
            id: this.currentNoteId,
            title: noteTitle,
            category: { id: categoryId },
            updatedAt: new Date().toISOString()
          }
          this.currentNote = updatedNote
          this.$message.success('保存成功')
        }
      } catch (err) {
        this.$message.error('保存失败，请重试')
      }
    },

    createNewNote(categoryId) {
      const newNoteId = 'new-note-' + Date.now().toString()
      this.currentNoteId = newNoteId
      this.currentCategoryId = categoryId || 'all'
      this.currentNote = {
        id: newNoteId,
        title: '新笔记',
        category: { id: categoryId || '' },
        updatedAt: new Date().toISOString()
      }
      this.content = '# 新笔记\n\n在这里开始写作...'

      // 如果是特定类别下创建，展开该类别
      if (categoryId) {
        this.expandedCategories[categoryId] = true
      }
    },

    addCategoryDialog() {
      this.showAddCategoryDialog = true
      this.newCategoryName = ''
    },

    async addCategory() {
      if (!this.newCategoryName.trim()) return

      try {
        const newCategory = await AddCategory(this.newCategoryName)
        await this.loadCategories()
        // 展开新添加的类别
        this.expandedCategories[newCategory.id] = true
        this.showAddCategoryDialog = false
      } catch (err) {
        console.error('添加类别失败:', err)
      }
    },

    confirmDeleteCategory(category) {
      this.categoryToDelete = category
      this.showDeleteCategoryConfirm = true
    },

    async deleteCategory() {
      if (!this.categoryToDelete) return
      try {
        await DeleteCategory(this.categoryToDelete.id)

        // 如果删除的是当前类别，切换到"全部笔记"
        if (this.currentCategoryId === this.categoryToDelete.id) {
          this.currentCategoryId = 'all'
        }

        await this.loadCategories()
        await this.loadNoteList()
        this.showDeleteCategoryConfirm = false
        this.categoryToDelete = null
        this.$message.success('删除成功')
      } catch (err) {
        this.$message.error('删除失败，请重试')
      }
    },

    extractTitle(markdown) {
      const firstLine = markdown.split('\n')[0]
      return firstLine.replace(/^#+\s*/, '').trim() || '无标题笔记'
    },

    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp * 1000); // 创建一个新的 Date 对象
      const year = date.getFullYear(); // 获取年份
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份，注意月份从0开始，所以加1
      const day = String(date.getDate()).padStart(2, '0'); // 获取日期
      return `${year}-${month}-${day}`; // 返回格式化后的日期
    },

    async handleImageAdd(filename, imagefile) {
      try {
        const base64Data = await this.getBase64(imagefile)
        const imageUrl = await this.$wails.Go.UploadImage({
          fileName: filename,
          data: base64Data
        })

        this.$refs.mdEditor.$img2Url(filename, imageUrl)
      } catch (err) {
        console.error('图片上传失败:', err)
      }
    },

    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result.split(',')[1])
        reader.onerror = error => reject(error)
      })
    },

    confirmDeleteNote(note) {
      this.noteToDelete = note
      this.showDeleteConfirm = true
    },

    async deleteNote() {
      if (!this.noteToDelete) return

      try {
        await DeleteNote(this.noteToDelete.id)

        // 如果删除的是当前打开的笔记，清空当前笔记
        if (this.currentNoteId === this.noteToDelete.id) {
          this.currentNoteId = ''
          this.currentNote = null
          this.content = ''
        }

        // 重新加载笔记列表
        await this.loadNoteList()
        this.showDeleteConfirm = false
        this.noteToDelete = null
        this.$message.success('删除成功')
      } catch (err) {
        this.$message.error('删除失败，请重试')
      }
    },

    async exportNote(format) {
      if (!this.currentNoteId) return

      try {
        const result = await ExportNote(this.currentNoteId, format)
        if (result) {
          this.$message.success('导出成功')
        }
      } catch (err) {
        this.$message.error('导出失败，请重试')
      }
    },

    async openExportDirectory() {
      try {
        await OpenExportDirectory()
        this.$message.success('打开导出目录成功')
      } catch (err) {
        this.$message.error('打开导出目录失败')
      }
    },

    confirmMoveNote(note) {
      this.noteToMove = note
      this.selectedTargetCategory = ''
      this.showMoveNoteDialog = true
    },

    async moveNote() {
      if (!this.noteToMove || !this.selectedTargetCategory) return

      try {
        const result = await MoveNote(this.noteToMove.id, this.selectedTargetCategory)
        if (result) {
          // 重新加载数据
          await this.loadNoteList()

          // 如果移动的是当前笔记，更新当前笔记信息
          if (this.currentNoteId === this.noteToMove.id) {
            this.currentNote.category = { id: this.selectedTargetCategory }
            this.currentCategoryId = this.selectedTargetCategory
          }

          this.showMoveNoteDialog = false
          this.noteToMove = null
          this.$message.success('移动成功')
        }
      } catch (err) {
        this.$message.error('移动失败，请重试')
      }
    },
  }
}
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
}

.sidebar {
  width: 280px;
  background: #f8f8f8;
  border-right: 1px solid #e0e0e0;
  overflow-y: auto;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  background: #f8f8f8;
  z-index: 1;
}

.category-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.category-header button {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
}

.category-actions {
  display: flex;
  gap: 8px;
}

.category-list {
  padding: 0;
  list-style: none;
  margin: 0;
  font-size: 14px;
  color: #333;
}

.category-list>li {
  border-bottom: 1px solid #eaeaea;
}

.category-item {
  padding: 12px 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: space-between;
  user-select: none;
  position: relative;
}

.category-item:hover {
  background: #f0f0f0;
}

.category-name {
  flex: 1;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 8px;
}

.note-count {
  font-size: 12px;
  color: #888;
  margin: 0 8px;
}

.toggle-icon {
  width: 16px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.delete-category-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 16px;
  cursor: pointer;
  padding: 0 5px;
  margin-left: 5px;
  opacity: 0;
  transition: opacity 0.2s;
}

.category-item:hover .delete-category-btn {
  opacity: 1;
}

.delete-category-btn:hover {
  color: #ff4d4f;
}

.note-list {
  list-style: none;
  padding: 0;
  margin: 0;
  background: #fff;
  border-top: 1px solid #eee;
}

.note-list li {
  padding: 10px 15px 10px 25px;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.note-list li:hover {
  background: #f9f9f9;
}

.note-list li.active {
  background: #e8f0fe;
  color: #1967d2;
}

.note-date {
  font-size: 11px;
  color: #999;
  margin-left: 8px;
}

.add-note {
  color: #666;
  font-style: italic;
  padding: 8px 15px 8px 25px;
}

.add-note:hover {
  color: #1967d2;
}

.markdown-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.toolbar {
  padding: 10px 15px;
  background: #f8f8f8;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.toolbar button {
  padding: 6px 12px;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  min-width: 60px;
}

.toolbar button:first-child {
  background: #1967d2;
}

.toolbar button:nth-child(2) {
  background: #28a745;
}

.toolbar button:nth-child(3) {
  background: #6c757d;
}

.toolbar button:nth-child(4) {
  background: #17a2b8;
}

.toolbar button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.note-title {
  font-weight: 500;
  color: #333;
  margin-left: auto;
  padding-right: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.welcome-screen {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
  padding: 20px;
  text-align: center;
}

.welcome-screen h2 {
  margin-bottom: 15px;
  color: #333;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999999;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 350px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 999999;
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.modal-content p {
  margin-bottom: 20px;
  color: #666;
}

.warning-text {
  color: #ff4d4f;
  font-weight: 500;
}

.modal-content input {
  width: 100%;
  padding: 10px;
  margin-bottom: 15px;
  box-sizing: border-box;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.modal-actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.modal-actions button:first-child {
  background: #ff4d4f;
  color: white;
}

.modal-actions button:last-child {
  background: #f0f0f0;
  color: #333;
}

.delete-note-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 16px;
  cursor: pointer;
  padding: 0 5px;
  margin-left: 5px;
  opacity: 0;
  transition: opacity 0.2s;
}

.note-list li:hover .delete-note-btn {
  opacity: 1;
}

.delete-note-btn:hover {
  color: #ff4d4f;
}

.note-title-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.note-actions {
  margin-left: 8px;
}

.category-select {
  width: 100%;
  padding: 8px;
  margin-bottom: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.more-actions-container {
  position: relative;
  display: inline-block;
}

.more-actions-menu {
  position: absolute;
  right: 0;
  top: 100%;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  min-width: 80px;
}

.more-actions-btn {
  background: none;
  border: none;
  color: #666;
  font-size: 16px;
  cursor: pointer;
  padding: 0 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.note-list li:hover .more-actions-btn {
  opacity: 1;
}

.more-actions-btn:hover {
  color: #1967d2;
}

.more-actions-menu button {
  display: block;
  width: 100%;
  padding: 8px 12px;
  text-align: left;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 13px;
  color: #333;
}

.more-actions-menu button:hover {
  background-color: #f5f5f5;
}
</style>